package com.czy.owner.ui.store;


import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.overlay.DrivingRouteOverlay;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.czy.owner.R;
import com.czy.owner.api.OwnerStoreInfoApi;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.StoreDetailBannersModel;
import com.czy.owner.entity.StoreDetailInfoModel;
import com.czy.owner.global.Constants;

import com.czy.owner.net.api.BaseResultEntity;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.net.utils.JsonUtil;
import com.czy.owner.net.utils.MyLoadView;
import com.czy.owner.permission.Acp;
import com.czy.owner.permission.AcpListener;
import com.czy.owner.permission.AcpOptions;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.ui.MainActivity;
import com.czy.owner.utils.GsonUtils;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.utils.StatusBarUtil;
import com.czy.owner.utils.glide.GlideUtils;
import com.czy.owner.widget.ImageCycleView;
import com.czy.owner.widget.MyScrollView;
import com.czy.owner.widget.UniversalDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * Created by wangyang on 2016/6/24 0024.
 */
public class BindStoreDetailActivity extends BaseActivity implements /*AMapNaviListener*/RouteSearch.OnRouteSearchListener, MyScrollView.ScrollViewLine {
    @BindView(R.id.myscrollview)
    MyScrollView myScrollView;
    @BindView(R.id.line_headview)
    LinearLayout lineHeadView;
    @BindView(R.id.img_store_view)
    ImageCycleView imgTop;
    @BindView(R.id.tv_store_number)
    TextView tvStoreNumber;
    @BindView(R.id.tv_store_adress)
    TextView tvStoreAdress;
    @BindView(R.id.tv_title_company_name)
    TextView tvTitleCompanyName;
    @BindView(R.id.tv_store_describe)
    TextView tvStoreDescribe;
    //    @ViewInject(R.id.floatinImgBtn)
//    private FloatingActionButton  floatingActionBtn;
    @BindView(R.id.mapview)
    MapView mapView;
    private AMap amap;
    //        private AMapNavi aMapNavi;
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    //标识，用于判断是否只显示一次定位信息和用户重新定位
    private boolean isFirstLoc = true;
    private boolean isLoad = true;
    private RouteSearch mRouteSearch;
    private LatLonPoint mStartPoint;//起点，
    private LatLonPoint mEndPoint;//终点，
    private MyLoadView myLoadView;
    private ArrayList<String> mImageUrl = null;
    private StoreDetailInfoModel.StoreInfoBean infoModel;
    private ArrayList<String> mImageUrlweb = new ArrayList<>();//banner的点击
    private List<StoreDetailBannersModel> bannersModel = new ArrayList<>();
    private static final int BANNER_TYPE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mapView.onCreate(savedInstanceState);// 此方法必须重写

    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_store_detail;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        if ((Build.VERSION.SDK_INT >= 23)) {
            onClickLocation();
        }
        setTitleLayout(lineHeadView);
        lineHeadView.setFocusable(true);
        lineHeadView.setFocusableInTouchMode(true);
        lineHeadView.requestFocus();
        lineHeadView.getBackground().setAlpha(0);//开始是透明的
        myScrollView.setScrollViewLine(this);
        StatusBarUtil.setTranslucentForImageViewInFragment(BindStoreDetailActivity.this, null);
        myLoadView = new MyLoadView(this, "正在加载");
        //获取地图对象
        amap = mapView.getMap();
//        aMapNavi = AMapNavi.getInstance(this);
//        aMapNavi.addAMapNaviListener(this);
//        重写onTouch()事件,在事件里通过requestDisallowInterceptTouchEvent(boolean)方法来设置父类的不可用,true表示父类的不可用
        //解决地图的touch事件和scrollView的touch事件冲突问题
//        mapView.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                if(event.getAction() == MotionEvent.ACTION_UP){
//                    myScrollView.requestDisallowInterceptTouchEvent(false);
//                }else{
//                    myScrollView.requestDisallowInterceptTouchEvent(true);
//                }
//                return false;
//            }
//        });
        mRouteSearch = new RouteSearch(this);
        mRouteSearch.setRouteSearchListener(this);
//        if(UserHelper.getInstance().getOwnerInfoModel(this).getBindStoreId()!=0){
//            floatingActionBtn.setVisibility(View.GONE);
//        }else {
//            floatingActionBtn.setVisibility(View.VISIBLE);
//        }
        getStoreInfoData();
        initLoc();
    }

    @Override
    protected void updateViews() {

    }


    //适配6.0的动态权限管理
    //打开位置权限

    public void onClickLocation() {
        Acp.getInstance(BindStoreDetailActivity.this).request(new AcpOptions.Builder().setPermissions(Manifest.permission.ACCESS_FINE_LOCATION).build(),
                new AcpListener() {
                    @Override
                    public void onGranted() {

                    }

                    @Override
                    public void onDenied(List<String> permissions) {

                        PhoneUtils.ShowToastMessage(BindStoreDetailActivity.this, permissions.toString() + "权限拒绝");
                    }
                });

    }

    //计算驾车路线
    private void calculateDriveRoute(LatLonPoint mStartPoint, LatLonPoint mEndPoint) {
        RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(mStartPoint, mEndPoint);
        // 第一个参数表示路径规划的起点和终点，第二个参数表示驾车模式，第三个参数表示途经点，第四个参数表示避让区域，第五个参数表示避让道路
        RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo, RouteSearch.DrivingDefault, null, null, "");
        mRouteSearch.calculateDriveRouteAsyn(query);// 异步路径规划驾车模式查询
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        myScrollView.requestDisallowInterceptTouchEvent(true);
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult result, int i) {
        MyLog.e("yang", "i==" + i + "\nresult==" + result);
        if (i == 1000) {
            if (result != null && result.getPaths() != null) {
                if (result.getPaths().size() > 0) {
                    final DrivePath drivePath = result.getPaths().get(0);
                    DrivingRouteOverlay drivingRouteOverlay = new DrivingRouteOverlay(
                            this, amap, drivePath,
                            result.getStartPos(),
                            result.getTargetPos());
                    drivingRouteOverlay.removeFromMap();
                    drivingRouteOverlay.addToMap();
                    drivingRouteOverlay.zoomToSpan();
                    drivingRouteOverlay.setNodeIconVisibility(false);
                }
            }
        }
    }

    @Override
    public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

    }

    @Override
    public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

    }

    private double latitude = 0.0;
    private double longitude = 0.0;

    //  定位回调监听事件
    AMapLocationListener mAMapLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {

                    //定位成功回调信息，设置相关消息
//                    amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                    latitude = amapLocation.getLatitude();//获取纬度
                    longitude = amapLocation.getLongitude();//获取经度

//                    amapLocation.getAccuracy();//获取精度信息
                    // 如果不设置标志位，此时再拖动地图时，它会不断将地图移动到当前的位置
                    if (isFirstLoc) {
                        //设置缩放级别
                        amap.moveCamera(CameraUpdateFactory.zoomTo(16));
                        //将地图移动到定位点
                        amap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude())));
                        //添加图钉
//                        amap.addMarker(getMarkerOptions(amapLocation));

                        mStartPoint = new LatLonPoint(amapLocation.getLatitude(), amapLocation.getLongitude());//起点，

                        getStoreInfoDriveRoute();
                    }

                } else {
                    //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                    Log.e("yang", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };

    //定位初始化控件配置
    private void initLoc() {
        locationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        locationClient.setLocationListener(mAMapLocationListener);
        //初始化定位参数
        locationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        locationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        locationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        locationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        locationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        locationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        locationClient.setLocationOption(locationOption);
        //启动定位
        locationClient.startLocation();

    }


    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();

    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != locationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            locationClient.stopLocation();
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
        mapView.onDestroy();
//        aMapNavi.stopNavi();
//        aMapNavi.destroy();
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @OnClick(R.id.img_back)
    public void imgBackOnClick(View view) {
        finish();
    }


    private void getStoreInfoData() {
        OwnerStoreInfoApi ownerStoreInfoApi = new OwnerStoreInfoApi(new HttpOnNextListener<StoreDetailInfoModel>() {
            @Override
            public void onNext(StoreDetailInfoModel model) {
                infoModel = model.getStoreInfo();
                setStoreInfoData(model);

            }

            @Override
            public void onCacheNext(String cache) {
                super.onCacheNext(cache);
                Gson gson = new Gson();
                Type type = new TypeToken<BaseResultEntity<StoreDetailInfoModel>>() {
                }.getType();
                BaseResultEntity<StoreDetailInfoModel> model = gson.fromJson(cache, type);
                infoModel = model.getData().getStoreInfo();
                setStoreInfoData(model.getData());
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                PhoneUtils.ShowToastMessage(BindStoreDetailActivity.this, e.getMessage());
            }

        }, this);
        ownerStoreInfoApi.setStoreId(SharedPreferencesUtils.getParam(BindStoreDetailActivity.this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "");
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(ownerStoreInfoApi);
    }


    private void setStoreInfoData(StoreDetailInfoModel infoModel) {
        tvTitleCompanyName.setText(infoModel.getStoreInfo().getStoreName());
        tvStoreDescribe.setText(infoModel.getStoreInfo().getDescription());
        String srtPhone = "电话: <font color='#09c0c7'>" + infoModel.getStoreInfo().getServiceNumber() + "</font>";
        String srtAddress = "地址: <font color='#09c0c7'>" + infoModel.getStoreInfo().getStoreLocation() + "</font>";
        tvStoreNumber.setText(Html.fromHtml(srtPhone));
        tvStoreAdress.setText(Html.fromHtml(srtAddress));
        mImageUrl = new ArrayList<>();
        mImageUrl.clear();
//        mImageUrlweb.clear();
        for (int i = 0; i < infoModel.getResList().size(); i++) {
            mImageUrl.add(infoModel.getResList().get(i).getResUrl() + "-320%7C1080");
//            mImageUrlweb.add(infoModel.getResList().get(i).getDescription());
        }
        imgTop.setImageResources(mImageUrl, mImageUrlweb, mAdCycleViewListener);
    }


    //规划路径
    private void getStoreInfoDriveRoute() {
        OwnerStoreInfoApi ownerStoreInfoApi = new OwnerStoreInfoApi(new HttpOnNextListener<StoreDetailInfoModel>() {
            @Override
            public void onNext(StoreDetailInfoModel model) {
                infoModel = model.getStoreInfo();
                mEndPoint = new LatLonPoint(infoModel.getGprsY(), infoModel.getGprsX());//终点
                calculateDriveRoute(mStartPoint, mEndPoint);
                isFirstLoc = false;
            }

            @Override
            public void onCacheNext(String cache) {
                super.onCacheNext(cache);
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                PhoneUtils.ShowToastMessage(BindStoreDetailActivity.this, e.getMessage());
            }

        }, this);
        ownerStoreInfoApi.setStoreId(SharedPreferencesUtils.getParam(BindStoreDetailActivity.this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "");
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(ownerStoreInfoApi);
    }

    private ImageCycleView.ImageCycleViewListener mAdCycleViewListener = new ImageCycleView.ImageCycleViewListener() {
        @Override
        public void onImageClick(int position, View imageView) {

            // TODO 单击图片处理事件
//            if (bannersModel.size() > 0) {
//                String contactType = bannersModel.get(position).getContactType();
//                if (contactType.equals("package")){
//                    Intent ti = new Intent(BindStoreDetailActivity.this, PackageCardDetailActivity.class);
//                    ti.putExtra("servicePackageId", Integer.valueOf(bannersModel.get(position).getContactId()));
//                    startActivity(ti);
//                }
//                else if (contactType.equals("card")){
//                    Intent ti = new Intent(BindStoreDetailActivity.this, BuyCardActivity.class);
//                    ti.putExtra("fromType",BANNER_TYPE);
//                    ti.putExtra("cardGroupId", Integer.valueOf(bannersModel.get(position).getContactId()));
//                    startActivity(ti);
//                }
//            }
        }

        @Override
        public void displayImage(String imageURL, final ImageView imageView) {
            GlideUtils.loadImage(BindStoreDetailActivity.this, imageURL, imageView, new GlideUtils.ImageLoadListener<String, GlideDrawable>() {
                @Override
                public void onLoadingComplete(String uri, ImageView view, GlideDrawable resource) {

                }

                @Override
                public void onLoadingError(String source, Exception e) {

                }
            }, R.mipmap.default_banner, R.mipmap.default_banner);


        }
    };


    //    高德导航
    @OnClick(R.id.img_navigation)
    public void imgNavigation(View view) {
        try {
            if ((Build.VERSION.SDK_INT >= 23)) {
                StoreUtils.onClickLocation(BindStoreDetailActivity.this, infoModel);
            } else {
                StoreUtils.imgNavigation(BindStoreDetailActivity.this, infoModel);
            }

        } catch (Exception e) {
            PhoneUtils.ShowToastMessage(BindStoreDetailActivity.this, "坐标设置错误");
        }

    }

    @OnClick(R.id.img_store_number)
    public void tvStoreNumberOnClick(View view) {
        if ((Build.VERSION.SDK_INT >= 23)) {
            onClickCallPhone();
        } else {
            ExitLoginDialog(infoModel.getServiceNumber(), "", "呼叫", "取消");
        }

    }

    public void onClickCallPhone() {
        Acp.getInstance(this).request(new AcpOptions.Builder().setPermissions(Manifest.permission.CALL_PHONE).build(),
                new AcpListener() {
                    @Override
                    public void onGranted() {
                        ExitLoginDialog(infoModel.getServiceNumber(), "", "呼叫", "取消");
                    }

                    @Override
                    public void onDenied(List<String> permissions) {
                        PhoneUtils.ShowToastMessage(BindStoreDetailActivity.this, permissions.toString() + "权限拒绝");

                    }
                });

    }

    private void ExitLoginDialog(final String title, String msg, String sure, String cancle) {
        new UniversalDialog(BindStoreDetailActivity.this).builder().setTitle(title)
//                .setMsg(msg)
                .setPositiveButton(sure, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_CALL);
                        intent.setData(Uri.parse("tel:" + title));
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);

                    }
                }).setNegativeButton(cancle, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).show();
    }

    protected void setTitleLayout(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            int statusBarHeight = getStatusBarHeight(BindStoreDetailActivity.this.getBaseContext());
            view.setPadding(0, statusBarHeight, 0, 0);

        }
    }

    /**
     * 获取状态栏高度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen",
                "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    @Override
    public void onScrollChanged(int l, int t, int oldl, int oldt) {
        if (oldt < 10) {
            lineHeadView.getBackground().setAlpha(0);
        } else if (oldt < 100 && oldt > 10) {
            lineHeadView.getBackground().setAlpha((int) (oldt / 8));
        } else if (oldt < 200 && oldt > 100) {
            lineHeadView.getBackground().setAlpha((int) (oldt / 6));

        } else if (oldt < 300 && oldt > 200) {
            lineHeadView.getBackground().setAlpha((int) (oldt / 4));
        } else if (oldt < 400 && oldt > 300) {
            lineHeadView.getBackground().setAlpha((int) (oldt / 2));
        } else if (oldt >= 400) {
            lineHeadView.getBackground().setAlpha(255);
        }
    }

}
